#!/usr/bin/python2.4
#
# Copyright 2008 Google Inc.
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#      http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""Root page."""

import wsgiref.handlers
import logging
import os
import instantvidsite
import browse

from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp import template

#static strings
logging.getLogger().setLevel(logging.DEBUG)

#TODO(gabe): add favorite video to user profile page


class UserProfile(webapp.RequestHandler):
  
  """serves the user profile page."""
  
  def get(self, sitepath):
    
    """get method for profile."""
    
    #find domain
    site = instantvidsite.GetSite(sitepath)
    if not site:
      logging.error('bad sitepath - '+str(sitepath))
      self.redirect("/?error=siteunknown")
      return
    
    user = users.GetCurrentUser()
    loggedin = user is not None
    user_videos = []
    userid = self.request.get('userid')
    #logging.debug('userprofile - dst- \''+userid+'\'')
    if (userid is None) or (userid == ''):
      self.redirect('/a/'+site.path+'/userlist')
      return
    
    # add known live user videos
    vids = instantvidsite.Video.gql("WHERE user = :1 AND status = :2 AND site = :3",
                               users.User(userid), 'live', site.key())
    user_videos = browse.ConvertVideosToDisplayObjects(vids)
    
    #get other user info
    #retrieve TubeUser, redir if none
    t_user = browse.GetTubeUser(site, users.User(userid))
    if not t_user:
      self.redirect('/a/'+site.path+'/userlist')
      return
           
    browse.PrintHeader(self.request, self.response, site, site.display_name+' - '+userid)
    
    template_values = {'userid': userid,
                       'user_videos': user_videos,
                       'site': site,
                       't_user': t_user,
                       'loggedin': loggedin}

    path = os.path.join(os.path.dirname(__file__), 'userprofile.html')
    self.response.out.write(template.render(path, template_values))

    
class UserDirectory(webapp.RequestHandler):
  
  """serves the user list page."""
  
  def get(self, sitepath):
    
    """serves the user profile page."""
    
    #find domain
    site = instantvidsite.GetSite(sitepath)
    if not site:
      logging.error('bad sitepath - '+str(sitepath))
      self.redirect("/?error=siteunknown")
      return

    user = users.GetCurrentUser()
    loggedin = user is not None
    
    #return list of known users - get name and featured video for each user
    t_users = instantvidsite.TubeUser.gql("WHERE site = :1", site.key())
           
    browse.PrintHeader(self.request, self.response, site, site.display_name + ' - users')
    
    template_values = {'t_users': t_users,
                       'loggedin': loggedin,
                       'site': site}

    path = os.path.join(os.path.dirname(__file__), 'userdirectory.html')
    self.response.out.write(template.render(path, template_values))
        
def main():
  application = webapp.WSGIApplication([(r'/a/([^/]*)/user', UserProfile),
                                        (r'/a/([^/]*)/userlist', UserDirectory)],
                                        debug=False)

  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
